

class EmployeeController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        
        def access = session.access
        access.refresh()
        if(access.hasDevAuth()){
             [ employeeInstanceList: Employee.list( params ), employeeInstanceTotal: Employee.count() ]
        }
        else if(access.hasAdminAuth()){
            [ employeeInstanceList: Employee.list( params ), employeeInstanceTotal: Employee.count() ]
        }
        else if(access.hasManagerAuth()){
            def list = Employee.findAllByHiredBy(access.area)
            println(list)
            [ employeeInstanceList: list, employeeInstanceTotal: list.count(), ]
        }
        else{
            flash.message = "Missing Authorization!"
            redirect(controller:'access', action:'login')
        }
    }

    def show = {
        def employeeInstance = Employee.get( params.id )
        
        if(!employeeInstance) {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            ArrayList a = employeeInstance.listOfProjects()                            //A list of whoas for this year
            Integer actualHours = employeeInstance.actualWorkingHoursPerYear()         //Can skip this and use employeeInstance.actualWorkingHoursPerYear() instead

            if(ModeAccess.isAvailableInCurrentMode(session.mode,employeeInstance.mode)){
                // If the employee mode corresponds to the current mode
                return [ employeeInstance : employeeInstance, whoaList : a, actualHours : actualHours]
            }
            else{
                flash.message = "Employee not accessible in current mode"
                redirect(action:list)
            }
        }
    }

    def delete = {
        def employeeInstance = Employee.get( params.id )
        if(employeeInstance) {
            try {
                employeeInstance.delete(flush:true)
                flash.message = "Employee ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Employee ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def employeeInstance = Employee.get( params.id )

        if(!employeeInstance) {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
        else {
             if(ModeAccess.isAvailableInCurrentMode(session.mode,employeeInstance.mode)){
                // If the employee mode corresponds to the current mode
               return [ employeeInstance : employeeInstance ]

            }
            else{
                flash.message = "Employee not accessible in current mode"
                redirect(action:list)
            }
            
        }
    }

    def update = {
        def employeeInstance = Employee.get( params.id )
        if(employeeInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(employeeInstance.version > version) {
                    
                    employeeInstance.errors.rejectValue("version", "employee.optimistic.locking.failure", "Another user has updated this Employee while you were editing.")
                    render(view:'edit',model:[employeeInstance:employeeInstance])
                    return
                }
            }
            employeeInstance.properties = params
            if(!employeeInstance.hasErrors() && employeeInstance.save()) {
                flash.message = "Employee ${params.id} updated"
                redirect(action:show,id:employeeInstance.id)
            }
            else {
                render(view:'edit',model:[employeeInstance:employeeInstance])
            }
        }
        else {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        if(session.access == "admin"){
            def employeeInstance = new Employee()
            employeeInstance.properties = params
            return ['employeeInstance':employeeInstance]
        }
        def access = session.access
        access.refresh()
       // if(access.hasAdminAuth()){
            def employeeInstance = new Employee()
            employeeInstance.properties = params
            return ['employeeInstance':employeeInstance]
        /*}
        else{
            flash.message = "Missing privilege for this action!"
            redirect(action:list)
        }*/
    }

    def save = {
         //Check that date of birth is correct
        if(params.dob_month.equals("4")||params.dob_month.equals("6")||params.dob_month.equals("9")||params.dob_month.equals("11")){
            if(params.dob_day.equals("31")){
                    params.dob_month = "ab"
            }
        }

        if(params.dob_month.equals("2")){ // check february month
            if(params.dob_day.equals("31")||params.dob_day.equals("30")){
                    params.dob_month = "ab"
            }
        }

        if(params.mode.equalsIgnoreCase("budget")){
            params.mode=0
        }
        else{
            params.mode=1
        }
        def employeeInstance = new Employee(params)

        if(!employeeInstance.hasErrors() && employeeInstance.save()){ // check constraints
                    flash.message = "Employee ${employeeInstance} created"
                    redirect(action:show,id:employeeInstance.id)
        }
        else {
            render(view:'create',model:[employeeInstance:employeeInstance])
        }

    }
   def updateFigures = {    //the numbers
        Float newFigure = Float.parseFloat(params.figure);

        def employeeInstance = Employee.get(params.id);

        if(params.type == "workPercentage"){
            employeeInstance.percentageWork = newFigure;
        }
        else{
           //  b.knownTotalIncome = newIncome;
        }
        if(projectInstance.save(flush:true)){

        }
        else{
             projectInstance.errors.each {
                  println(it);
                }
                b.errors.each {
                 println(it);
                }
        }

        redirect(action:blank);

    }
}